import md5 from "md5";
const onmessage = async (e) => {
    console.log("加速运转！启动！");
    const { file, chunkSize, startIndex, endIndex } = e.data;
    const result = [];
    //从传入的起始位置和结束位置为点，定位好切片最终返回值的位置
    for (let i = startIndex; i < endIndex; i++) {
        let chunk = await getChunk(file, chunkSize, i);
        result.push(chunk);
    }
    self.postMessage(result);
};
self.addEventListener("message", onmessage);
const getChunk = (file, size, index) => {
    return new Promise((resolve) => {
        //1.计算当前分片初始位置和结束位置
        const start = index * size;
        const end = start + size;
        //2.拿到对应位置file的块
        const chunkFile = file.slice(start, end);
        //3.通过文件读取器，读取成arrbuffer，进行hash加密，用于和后端校验，保证文件安全性和完整性
        const reader = new FileReader();
        reader.onload = (e) => {
            const arrbuffer = e.target.result;
            const uint8Array = new Uint8Array(arrbuffer);
            const buffer = Buffer.from(uint8Array);
            const hash = md5(buffer);
            resolve({ start, end, chunkFile, index, hash });
        };
        reader.readAsArrayBuffer(chunkFile);
    });
};
